//
//  THDetailOfHistoryViewController.m
//  Teacher-Help
//
//  Created by Taro on 15/11/8.
//  Copyright © 2015年 Taro. All rights reserved.
//

#import "THDetailOfHistoryViewController.h"
#import "XYPieChart.h"
#import "NSDictionary+QuickCreat.h"
#import <AFNetworking/AFNetworking.h>
#import "THhistory.h"
@interface THDetailOfHistoryViewController ()<XYPieChartDataSource,XYPieChartDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic , strong) UIView * firstView;
@property (nonatomic , strong) UIView * secondView;


@property (nonatomic , strong) XYPieChart * pieChart;
@property (nonatomic , strong) NSArray * slice;
@property (nonatomic , strong) NSArray * nameOfSlice;
@property (nonatomic , strong) NSArray * colorOfSlice;
@property (nonatomic , strong) UITableView * recordTableView;
@property (nonatomic , strong) UITableView * homeworkTableView;

@property (nonatomic , strong) UISegmentedControl * segment;


@property (nonatomic , weak) UITextField * gradeOfStudent;
@property (weak,nonatomic) UIButton *doneInKeyboardButton;


@property (nonatomic , strong) NSNumber * absenceProportion;
@property (nonatomic , strong) NSNumber * lateProportion;
@property (nonatomic , strong) NSNumber * leaveProportion;
@property (nonatomic , strong) NSNumber * appearProportion;
@property (nonatomic , strong) NSArray * historyModel;
@property (nonatomic , strong) NSMutableDictionary * submitData;
@property (nonatomic , strong) UIButton * submit;



@end

@implementation THDetailOfHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor whiteColor];
    _firstView = [[UIView alloc] initWithFrame:self.view.frame];
    _secondView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_secondView];
    [self.view addSubview:_firstView];
    // Do any additional setup after loading the view.
    self.tabBarController.tabBar.hidden = YES;
    self.firstView.backgroundColor = [UIColor whiteColor];
    self.secondView.backgroundColor = [UIColor orangeColor];
    NSArray *segmentData = @[@"考勤",@"作业"];
    _segment = [[UISegmentedControl alloc] initWithItems:segmentData];
    self.navigationItem.titleView = _segment;
    [_segment setBackgroundColor:XColor(64, 185, 216, 1)];
    [_segment setTintColor:[UIColor whiteColor]];
    _segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(didSelectSegment:) forControlEvents:UIControlEventValueChanged];
    
    _submit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _submit.frame = CGRectMake(0, 0, 50, 30);
    [_submit setTitle:@"提交" forState:UIControlStateNormal];
    _submit.hidden = YES;
    [_submit addTarget:self action:@selector(submitDateToServe) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_submit];
    self.navigationItem.rightBarButtonItem = item;
    self.recordTableView = [[UITableView alloc] init];
    self.recordTableView.delegate = self;
    self.recordTableView.dataSource = self;
    self.recordTableView.frame = CGRectMake(0,screenH/2, screenW, screenH/2);
    [self.firstView addSubview:self.recordTableView];
    
   
//
    [self addNameOfStudent];
    
    [self getDataFromServe:^(NSMutableDictionary *dictionary) {
        _absenceProportion = dictionary[@"absenceProportion"];
        _lateProportion = dictionary[@"lateProportion"];
        _leaveProportion = dictionary[@"leaveProportion"];
        _appearProportion = dictionary[@"appearProportion"];
        NSArray *historyArray = dictionary[@"history"];
        THLog(@"%ld",historyArray.count);
        THLog(@"%@--%@--%@--%@",_absenceProportion,_lateProportion,_leaveProportion,_appearProportion);
       [self addPieChartToView];
        NSMutableArray *model = [NSMutableArray array];
        for (NSDictionary *dict in historyArray) {
            THhistory *history = [THhistory historyWithDic:dict];
            [model addObject:history];
        }
        _historyModel = model;
        
       [self.recordTableView reloadData];
       [self.homeworkTableView reloadData];
        _submitData = [NSMutableDictionary dictionaryWithCapacity:_historyModel.count];
    }];
    
   
    
}

- (void)addNameOfStudent{
   
    self.homeworkTableView = [[UITableView alloc] init];
    self.homeworkTableView.frame = CGRectMake(0, 64+50, screenW, screenH-64-36-100);
    self.homeworkTableView.backgroundColor = [UIColor grayColor];
    self.homeworkTableView.dataSource = self;

    self.homeworkTableView.delegate = self;
//    self.homeworkTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.secondView addSubview:self.homeworkTableView];
    
   
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.recordTableView) {
        return 100;
    }else if(tableView == self.homeworkTableView){
        return 45;
    }
    return 0;
    
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return _historyModel.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ID = [NSString stringWithFormat:@"cell%ld",indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        THhistory *history = _historyModel[indexPath.row];
        if (tableView == self.recordTableView) {
            NSString *name = [NSString stringWithFormat:@"姓名 :%@",history.name];
            NSString *studentId = [NSString stringWithFormat:@"学号 :%@",history.studentNo];
            NSArray *title = [NSArray arrayWithObjects:studentId,name, nil];
            for (int i = 0; i < title.count; i++) {
                UILabel *label = [[UILabel alloc] init];
                label.text = [title objectAtIndex:i];
                label.frame = CGRectMake(i*screenW/2, 0, screenW/2, 50);
                [cell addSubview:label];
                
            }
            
            
            
            NSString *late = [NSString stringWithFormat:@"迟到%@",history.late];
            NSString *absence = [NSString stringWithFormat:@"缺勤%@",history.absence];
            NSString *appear = [NSString stringWithFormat:@"到勤%@",history.appear];
            NSString *leave = [NSString stringWithFormat:@"请假%@",history.leave];
            
            NSArray *detail = [NSArray arrayWithObjects:appear,absence,late,leave, nil];
            NSArray *colorOfLabel = [NSArray arrayWithObjects:XColor(246, 155, 0, 1),XColor(129, 195, 29, 1),XColor(62, 173, 219, 1),XColor(229, 66, 115, 1),nil];
            
            
            for (int i = 0; i < detail.count; i++) {
                UILabel *label = [[UILabel alloc] init];
                label.text = [detail objectAtIndex:i];
                label.frame = CGRectMake(screenW/4*i, 50, screenW/4, 50);
                label.backgroundColor = [colorOfLabel objectAtIndex:i];
                [cell addSubview:label];
                
            }
            
            
            
        }else if(tableView == _homeworkTableView){
            UILabel *label = [[UILabel alloc] init];
            label.frame = CGRectMake(0, 0, screenW/2, cell.frame.size.height);
            [cell addSubview:label];
            
            label.text = [NSString stringWithFormat:@"%@  %@",history.studentNo,history.name];
            
            
            UITextField *textField = [[UITextField alloc] init];
            textField.tag = indexPath.row;
            textField.frame = CGRectMake(screenW*2/3, 5, screenW/3-5, cell.frame.size.height-10);
            //        UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
            //        UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
            textField.keyboardType = UIKeyboardTypeNumberPad;
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.text = history.grades;
            [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
            _gradeOfStudent = textField;
            _gradeOfStudent.delegate = self;
            cell.accessoryView = textField;
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else
      {
         while ([cell.contentView.subviews lastObject] != nil)
          {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
          }
       }

   
    return cell;
}

- (void) textFieldDidChange: (id)sender{
//    NSNumber *textFieldTag = [NSNumber numberWithInteger:[sender tag]];
    UITextField *field = (UITextField *)sender;
    THhistory *history = [_historyModel objectAtIndex:[sender tag]];
    history.grades = field.text;
    [_submitData setValue:history.grades forKey:[NSString stringWithFormat:@"%@",history.studentId]];
    THLog(@"dict == %@",_submitData);
     
    
    
//    THLog(@"ssss%@",textFieldTag);
//    THLog(@"sdadad%@",field.text);
    
}


- (void)addPieChartToView{
    _pieChart = [[XYPieChart alloc] init];
    _pieChart.dataSource = self;
 
    
    _slice = [NSArray arrayWithObjects:_absenceProportion,_leaveProportion,_lateProportion,_appearProportion, nil];
//    _slice = [NSArray arrayWithObjects:@0.2,@0.3,@0.2,@0.3,nil];
    _nameOfSlice = [NSArray arrayWithObjects:@"缺席",@"请假",@"迟到",@"已到", nil];
    [_pieChart setStartPieAngle:M_PI];
    [_pieChart setAnimationSpeed:1.0];
    [_pieChart setPieCenter:CGPointMake(screenW/2, screenH/3)];
    [_pieChart setLabelFont:[UIFont fontWithName:@"DBLCDTempBlack" size:20]];
    CGFloat R  = screenW/3-20;
    [_pieChart setPieRadius:R];
    [_pieChart setLabelRadius:R-20];
    [_pieChart setShowPercentage:YES];
    [_pieChart setShowLabel:YES];
    [_pieChart setPieBackgroundColor:[UIColor colorWithWhite:0.95 alpha:1]];
    [_pieChart setLabelShadowColor:[UIColor blackColor]];
    self.colorOfSlice = [NSArray arrayWithObjects:XColor(246, 155, 0, 1),XColor(129, 195, 29, 1),XColor(62, 173, 219, 1),XColor(229, 66, 115, 1),nil];
    [self.pieChart reloadData];
    [self.firstView addSubview:self.pieChart];
    
}


- (void)didSelectSegment:(UISegmentedControl *)seg{
    
    if (seg.selectedSegmentIndex == 0) {
        self.firstView.hidden = NO;
        self.secondView.hidden = YES;
        _submit.hidden = YES;
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }else if(seg.selectedSegmentIndex == 1){
        self.firstView.hidden = YES;
        self.secondView.hidden = NO;
        _submit.hidden = NO;
    }
}


- (void)submitDateToServe{
    
}



//网络请求
- (void)getDataFromServe:(void(^)( NSMutableDictionary *dictionary))success{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    NSDictionary* bodyParameters = @{
                                     @"courseId":_courseId,
                                     };
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://120.26.83.51/demo/get_history/" parameters:bodyParameters constructingBodyWithBlock:nil error:NULL];
    
    // Add Headers
    [request setValue:_cookie forHTTPHeaderField:@"Cookie"];
    
    // Fetch Request
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dict = responseObject;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (success) {
                success(dict);
            }
        }];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"HTTP Request failed: %@", error);
                                                                         }];
    
    [manager.operationQueue addOperation:operation];
    
}


- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart

{
    
    
    
    return self.slice.count;
    
}



- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index

{
    
    return [[self.slice objectAtIndex:index] floatValue];
    
}



- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index

{
    
    return [self.colorOfSlice objectAtIndex:(index % self.colorOfSlice.count)];
    
}



- (NSString *)pieChart:(XYPieChart *)pieChart textForSliceAtIndex:(NSUInteger)index{
    
    return [self.nameOfSlice objectAtIndex:index];
    
}




- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//     [_doneInKeyboardButton removeFromSuperview];
    
}

//设置键盘

- (void)viewWillAppear:(BOOL)animated {
    
//    //注册键盘显示通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
//    //注册键盘隐藏通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [super viewWillAppear:animated];
     [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

//- (void)handleKeyboardDidShow:(NSNotification *)notification
//{
//    // NSNotification中的 userInfo字典中包含键盘的位置和大小等信息
//    NSDictionary *userInfo = [notification userInfo];
//    // UIKeyboardAnimationDurationUserInfoKey 对应键盘弹出的动画时间
//    CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    // UIKeyboardAnimationCurveUserInfoKey 对应键盘弹出的动画类型
//    NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
//    //数字彩,数字键盘添加“完成”按钮
//    if (_doneInKeyboardButton){
//        
//        [UIView beginAnimations:nil context:NULL];
//        [UIView setAnimationDuration:animationDuration];//设置添加按钮的动画时间
//        [UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];//设置添加按钮的动画类型
//        
//        //设置自定制按钮的添加位置(这里为数字键盘添加“完成”按钮)
//        _doneInKeyboardButton.transform=CGAffineTransformTranslate(_doneInKeyboardButton.transform, 0, -53);
//        
//        [UIView commitAnimations];
//    }
//    
//}
//- (void)handleKeyboardWillHide:(NSNotification *)notification
//{
//    THLog(@"%s",__func__);
//    // NSNotification中的 userInfo字典中包含键盘的位置和大小等信息
//    NSDictionary *userInfo = [notification userInfo];
//    // UIKeyboardAnimationDurationUserInfoKey 对应键盘收起的动画时间
//    CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    
//    if (_doneInKeyboardButton.superview)
//    {
//        [UIView animateWithDuration:animationDuration animations:^{
//            //动画内容，将自定制按钮移回初始位置
//            _doneInKeyboardButton.transform=CGAffineTransformIdentity;
//        } completion:^(BOOL finished) {
//            //动画结束后移除自定制的按钮
//            [_doneInKeyboardButton removeFromSuperview];
//        }];
//        
//    }
//}
//
//
//- (void)textFieldDidBeginEditing:(UITextField *)textField{
//    THLog(@"%s",__func__);
//    textField = self.gradeOfStudent;
//    [self configDoneInKeyBoardButton];
//}
//
//
//- (void)configDoneInKeyBoardButton{
//    
//    THLog(@"%s",__func__);
//    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
//    //初始化
//    if (_doneInKeyboardButton == nil)
//    {
//        _doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_doneInKeyboardButton setTitle:@"NEXT" forState:UIControlStateNormal];
//        [_doneInKeyboardButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        
//        _doneInKeyboardButton.frame = CGRectMake(0, screenHeight, 106, 53);
//        
//        _doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
//        [_doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
//    }
//    //每次必须从新设定“完成”按钮的初始化坐标位置
//    _doneInKeyboardButton.frame = CGRectMake(0, screenHeight, 106, 53);
//    
//    //由于ios8下，键盘所在的window视图还没有初始化完成，调用在下一次 runloop 下获得键盘所在的window视图
//    [self performSelector:@selector(addDoneButton) withObject:nil afterDelay:0.0f];
//    
//    
//}
//
//- (void) addDoneButton{
//    //获得键盘所在的window视图
//    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
//    [tempWindow addSubview:_doneInKeyboardButton];    // 注意这里直接加到window上
//    
//}
//-(void)finishAction{
//    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
//}
@end
